<script setup>
import { ref, watch, computed, provide, onMounted, inject } from 'vue'
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router'
import { useChatStore } from '@/stores/chat'
import { useAuthStore } from '@/stores/auth'
import { useConfigStore } from '@/stores/config'

import Drawer from '@/components/common/Drawer.vue'
import Sessions from '@/components/chat/Sessions.vue'

const route = useRoute()
const router = useRouter()
const isSmallPage = inject('isSmallPage')

const authStore = useAuthStore()
const chatStore = useChatStore()
const configStore = useConfigStore()

const drawerRef = ref(null)

const sessionId = computed(() => parseInt(route.params?.id || 0))
const createSession = () => {
  authStore.authOrLogin(
    async () => {
      try {
        const data = await chatStore.create()
        router.push({ name: 'chatChat', params: { id: data.id } })
      } catch (err) {
        //取消创建
      }
    },
    {
      router,
      options: { confirm: true, redirect: route.fullPath },
    }
  )
}

const renameSession = async (id) => {
  try {
    await chatStore.rename(id)
  } catch (err) {
    //取消重命名
  }
}

const removeSession = async (id) => {
  try {
    await chatStore.remove(id)
    //回到首页
    router.replace({ name: 'chatIndex' })
  } catch (err) {
    //取消删除
  }
}

//首次进入页面时的路由导航
const firstNavigate = async () => {
  if (route.name === 'chat') {
    if (chatStore.active?.id > 0 && authStore.isAuthenticated) {
      //进入最近一次的会话
      router.replace({ name: 'chatChat', params: { id: chatStore.active.id } })
    } else {
      //进入首页
      router.replace({ name: 'chatIndex' })
    }
  } else if (route.name === 'chatChat') {
    try {
      if (chatStore.active?.id !== Number(route.params.id)) {
        await chatStore.getSession(route.params.id)
      }
    } catch (err) {
      console.error('err', err)
      router.replace({ name: 'chatIndex' })
    }
  }
}

//用户登出后，路由变化
watch(
  () => authStore.isAuthenticated,
  (value) => {
    if (!value && route.name !== 'chatIndex') {
      router.replace({ name: 'chatIndex' })
    }
  }
)

//子路由守卫
onBeforeRouteUpdate(async (to, from, next) => {
  switch (to.name) {
    //进入对话页
    case 'chatChat':
      try {
        if (!authStore.isAuthenticated) {
          next({ name: 'chatIndex' })
        } else {
          if (chatStore.active?.id !== Number(to.params.id)) {
            await chatStore.getSession(to.params.id)
          }
          next()
        }
      } catch (err) {
        //出错
        console.error('err', err)
        next(false)
      }
      break
    //进入首页
    case 'chat':
      next({ name: 'chatIndex' })
      break
    default:
      next()
  }
})

onMounted(async () => {
  if (authStore.isAuthenticated) {
    await chatStore.init()
  }

  firstNavigate()
})

provide('session', {
  create: createSession,
  remove: removeSession,
  rename: renameSession,
})

provide('drawerRef', drawerRef)
</script>

<template>
  <div class="flex h-full bg-[--el-fill-color-lighter] text-[--el-text-color-primary]">
    <Drawer ref="drawerRef" width="w-60">
      <Sessions
        :id="sessionId"
        :data="chatStore.data"
        @rename="renameSession"
        @remove="removeSession"
        @create="createSession"
      />
    </Drawer>
    <div class="w-full overflow-hidden">
      <RouterView />
    </div>
  </div>
</template>
